<?php

namespace common\models\c2\entity;

use common\models\c2\statics\ProductType;
use kzo\base\components\events\LinkManyBehavior;
use kzo\base\models\statics\EntityModelStatus;
use kzo\user\models\BeUser;
use Yii;
use yii\behaviors\BlameableBehavior;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%product}}".
 *
 * @property string $id
 * @property integer $type
 * @property string $sku
 * @property string $name
 * @property string $label
 * @property string $factory_price
 * @property string $supplier_id
 * @property string $currency_id
 * @property string $measure_id
 * @property string $description
 * @property integer $sold_count
 * @property string $created_by
 * @property string $updated_by
 * @property integer $status
 * @property integer $position
 * @property string $created_at
 * @property string $updated_at
 */
class SaleProduct extends Product
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%product}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['type', 'supplier_id', 'currency_id', 'measure_id', 'sold_count', 'created_by', 'updated_by', 'status', 'position'], 'integer'],
            [['name', 'attributeset_ids', 'sku'], 'required'],
            [['factory_price'], 'number'],
            [['description'], 'string'],
            [['sku', 'name', ], 'unique'],
            [['created_at', 'updated_at', 'attributeset_ids'], 'safe'],
            [['sku', 'name', 'label'], 'string', 'max' => 255],
            [['sku'], 'match', 'pattern' => '/^[A-Za-z0-9_-]+$/u'],
            [['sku'], 'match', 'pattern' => '/[\x{4e00}-\x{9fa5}]+/u', 'not' => true],
        ];
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'attributesetBehavior' => [
                'class' => LinkManyBehavior::className(),
                'relation' => 'attributesets',
                'relationReferenceAttribute' => 'attributeset_ids',
                'extraColumns' => [
                    'created_at' => function() {
                        return date('Y-m-d H:i:s');
                    },
                    'updated_at' => function() {
                        return date('Y-m-d H:i:s');
                    },
                ],
            ],
            'eavBehavior' => [
                'class' => \common\components\behaviors\EavBehavior::className(),
                'vModelClass' => ProductEav::className(),
                'aModelClass' => Attribute::className(),
            ],
            'metaEavAttributesBehavior' => [
                'class' => LinkManyBehavior::className(),
                'relation' => 'metaEavAttributes', // relation, which will be handled
                'relationReferenceAttribute' => 'meta_attributes_ids', // virtual attribute, which is used for related records specification
                'extraColumns' => [
                    'created_at' => function() {
                        return date('Y-m-d H:i:s');
                    },
                    'updated_at' => function() {
                        return date('Y-m-d H:i:s');
                    },
                ],
            ],
        ]); // TODO: Change the autogenerated stub
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app.c2', 'ID'),
            'type' => Yii::t('app.c2', 'Type'),
            'sku' => Yii::t('app.c2', 'Sku'),
            'name' => Yii::t('app.c2', 'Name'),
            'label' => Yii::t('app.c2', 'Label'),
            'factory_price' => Yii::t('app.c2', 'Factory Price'),
            'supplier_id' => Yii::t('app.c2', 'Supplier ID'),
            'currency_id' => Yii::t('app.c2', 'Currency ID'),
            'measure_id' => Yii::t('app.c2', 'Measure ID'),
            'description' => Yii::t('app.c2', 'Description'),
            'sold_count' => Yii::t('app.c2', 'Sold Count'),
            'created_by' => Yii::t('app.c2', 'Created By'),
            'updated_by' => Yii::t('app.c2', 'Updated By'),
            'status' => Yii::t('app.c2', 'Status'),
            'position' => Yii::t('app.c2', 'Position'),
            'created_at' => Yii::t('app.c2', 'Created At'),
            'updated_at' => Yii::t('app.c2', 'Updated At'),
        ];
    }

    /**
     * @inheritdoc
     * @return \common\models\c2\query\ProductQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \common\models\c2\query\ProductQuery(get_called_class());
    }

    /**
     * setup default values
     **/
    public function loadDefaultValues($skipIfSet = true)
    {
        parent::loadDefaultValues($skipIfSet);
        $this->type = ProductType::TYPE_PRODUCT;
    }


    public function getMetaEavAttributes($condition = [])
    {
        return $this->hasMany(Attribute::className(), ['id' => 'attribute_id'])
            ->where(['status' => EntityModelStatus::STATUS_ACTIVE])
            ->where($condition)
            ->viaTable('{{%product_eav}}', ['entity_id' => 'id'])
            ->orderBy(['position' => SORT_DESC]);
    }

    public function getNonSkuMetaAttributes()
    {
        return $this->getMetaEavAttributes(['is_sku' => 0]);
    }

    public function getAttributesets()
    {
        return $this->hasMany(Attributeset::className(), ['id' => 'attributeset_id'])
            ->where(['status' => EntityModelStatus::STATUS_ACTIVE])
            ->viaTable('{{%product_attributeset_rs}}', ['product_id' => 'id']);
    }

    /**
     * retrieve meta attributes according to attributesets
     * @return array attributes
     */
    public function getAttributesetAttributes() {
        if (!isset($this->_data['META_ATTRIBUTES'])) {
            $data = [];
            foreach ($this->attributesets as $attributeset) {
                foreach ($attributeset->attrs as $attr) {
                    if (!isset($data[$attr->code])) {
                        $data[$attr->code] = $attr;
                    }
                }
            }
            $this->_data['META_ATTRIBUTES'] = $data;
        }
        return $this->_data['META_ATTRIBUTES'];
    }

}
